package com.company.Nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class NioServer {

    public static void main(String[] args) throws Exception {
        //1.得到一个serverSocketChannel对象
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //2.得到一个选择器对象Selector
        Selector selector = Selector.open();
        //3.绑定端口号
        serverSocketChannel.bind(new InetSocketAddress(9999));
        //4.设置非阻塞
        serverSocketChannel.configureBlocking(false);
        //5.注册selector
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);//检测是否有客户端连接

        //6.干活
        while (true) {
            //6.1监控客户端
            if (selector.select(2000) == 0) {//无客户端连接 nio非阻塞 超时时间毫秒
                System.out.println("server 没有客户端，做别的事");
                continue;
            }

            //6.2 得到selectionKey，判断通道中的事件
            Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();//获取所有的key对应服务器
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();

                if (key.isAcceptable()) {//客户端连接事件
                    System.out.println("OP_ACCEPT");
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    //注册服务端的读时间 第三个参数接受客户端发来的附件信息
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));

                }

                if (key.isReadable()) { //读的事件
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = (ByteBuffer) key.attachment();//接收附件
                    channel.read(buffer);//从客户端读取数据
                    System.out.println("客户端发来数据：" + new String(buffer.array()));
                }

                //6.3手动从集合中移除key，防止重复处理
                keyIterator.remove();

            }


        }

    }

}
